package com.mikhailenko.transportMVC.service.impl;

import java.util.List;





import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mikhailenko.transportMVC.exeption.GroupNotFoundExeption;
import com.mikhailenko.transportMVC.model.Group;
import com.mikhailenko.transportMVC.repository.GroupRepository;
import com.mikhailenko.transportMVC.service.GroupService;

@Service
public class GroupServiceImpl implements GroupService{

    @Autowired
    private GroupRepository groupRepository;
    
    @Override
    @Transactional
    public Group create(Group group) {
        Group createdGroup = group;
        return groupRepository.saveAndFlush(createdGroup);
    }

    @Override
    @Transactional(rollbackFor = GroupNotFoundExeption.class)
    public Group delete(int id) throws GroupNotFoundExeption {
        Group deletedGroup = groupRepository.findOne(id);
        
        if (deletedGroup == null){
            throw new GroupNotFoundExeption();
        }
        
        groupRepository.delete(id);
        return deletedGroup;
    }

    @Override
    @Transactional
    public List<Group> findAll() {
        return groupRepository.findAll();
    }

    @Override
    @Transactional(rollbackFor = GroupNotFoundExeption.class)
    public Group update(Group group) throws GroupNotFoundExeption {
        Group updatedGroup = groupRepository.findOne(group.getId());
        
        if (updatedGroup == null){
            throw new GroupNotFoundExeption();
        }
        
        updatedGroup.setName(group.getName());
        
        return updatedGroup;
    }

    @Override
    @Transactional
    public Group findById(int id) {
        return groupRepository.findOne(id);
    }

    @Override
    @Transactional
    public Group findByName(String name) {
        return groupRepository.findByName(name);
    }

}
